<template>
  <div
    ref="chartRef"
    :style="{ width: props.width, height: props.height }"
  ></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import { debounce } from "lodash";

const emit = defineEmits(["chart-click"]);
// 柱状图和折线图

const props = defineProps({
  // 图表类型: bar-柱状图, line-折线图
  type: {
    type: String,
    default: "bar",
  },
  // 图表数据
  data: {
    type: Array,
    required: true,
  },
  // x轴数据
  xAxis: {
    type: Array,
    required: true,
  },
  // 图表标题
  title: {
    type: String,
    default: "",
  },
  // 图表宽度
  width: {
    type: String,
    default: "100%",
  },
  // 图表高度
  height: {
    type: String,
    default: "280px",
  },
  // 方向：1-竖向，2-横向
  direction: {
    type: Number,
    default: 1,
  },
  // 柱状图宽度
  barWidth: {
    type: Number,
    default: 20,
  },
  isClick: {
    type: Boolean,
    default: false,
  },
});

const chartRef = ref(null);
let chart = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  updateChart();

  chart.on("click", (params) => {
    if (params.componentType === "series") {
      emit("chart-click", params.data);
    }
  });
};

// 更新图表配置
const updateChart = () => {
  const isHorizontal = props.direction === 2;

  const primaryBgColor = "#21aba5";

  const option = {
    title: {
      text: props.title,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      top: props.direction === 2 ? "6%" : "10%",
      left: "4%",
      right: "8%",
      bottom: "9%",
      containLabel: true,
    },
    xAxis: {
      type: isHorizontal ? "value" : "category",
      data: isHorizontal ? null : props.xAxis,
      boundaryGap: isHorizontal ? "20%" : true, // 根据坐标轴类型设置不同的 boundaryGap
      min: isHorizontal ? 0 : null, // 横向时，为数值轴设置最小值
    },
    yAxis: {
      type: isHorizontal ? "category" : "value",
      data: isHorizontal ? props.xAxis : null,
      min: isHorizontal ? null : 0, // 纵向时，为数值轴设置最小值
    },
    color: [primaryBgColor],
    series: [
      {
        type: props.type,
        data: props.data,
        smooth: props.type === "line",
        barWidth: props.barWidth, // 设置柱状图宽度为20像素
        label: {
          show: true, // 显示标签
          position: props.direction === 1 ? "top" : "right", // 将标签放置于顶部位置
        },
      },
    ],
  };

  chart?.setOption(option);
};

// 监听数据变化
watch(
  () => props,
  () => updateChart(),
  { deep: true }
);

window.addEventListener(
  "resize",
  debounce(() => {
    chart?.resize();
  }, 200)
);

// 组件挂载时初始化
onMounted(() => {
  initChart();
});

// 组件卸载时销毁实例
onUnmounted(() => {
  chart?.dispose();
  window.removeEventListener("resize", () => {
    chart?.resize();
  });
});
</script>

<style scoped>
</style>

